﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text;
using ABC.Domain.Entities;

public static class ValidationExtensions
{
    public static MvcHtmlString ValidationMessageDialogFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string errorClass = "error")
    {
        string elementName = ExpressionHelper.GetExpressionText(expression);
        MvcHtmlString normal = html.ValidationMessageFor(expression);
        if (normal != null)
        {
            string newValidator = Regex.Replace(normal.ToHtmlString(), @"<span([^>]*)>([^<]*)</span>", string.Format("<label for=\"{0}\" $1>$2</label>", elementName), RegexOptions.IgnoreCase);


            //<div class="alert alert-error fade in">
            //    <button data-dismiss="alert" class="close">×</button>
            //    <strong>Ошибка!</strong> Поле Phone должно соответствовать регулярному выражению "\+[0-9]{7,12}"..
            //</div>

            if (!string.IsNullOrWhiteSpace(errorClass))
                newValidator = newValidator.Replace("field-validation-error", errorClass);


            return MvcHtmlString.Create(newValidator);
        }
        return null;
    }


    public static MvcHtmlString ValidationSummaryDialog(this HtmlHelper html)
    {
        if (!html.ViewData.ModelState.IsValid)
        {
            var sb = new StringBuilder();
            foreach (var t in html.ViewData.ModelState.Keys.Where(field => !html.ViewData.ModelState.IsValidField(field)).SelectMany(field => html.ViewData.ModelState[field].Errors))
            {
                sb.AppendLine("<div class=\"alert alert-error\">");
                sb.AppendLine("<button data-dismiss=\"alert\" class=\"close\">×</button>");
                sb.AppendLine("<ul class=\"unstyled\"><li>");
                sb.AppendLine("<strong>Ошибка!</strong>");
                sb.AppendLine(t.ErrorMessage);
                sb.AppendLine("</li></ul></div>");
            }
            return MvcHtmlString.Create(sb.ToString());
        }
        return MvcHtmlString.Empty;
    }

    public static MvcHtmlString Paging(this HtmlHelper htmlHelper, int pageNumber, int pageCount, Func<int, string> pageUrl)
    {
        int pageStart, pageEnd;
        pageStart = ((pageNumber - 1) / 6) * 6 + 1;
        pageEnd = pageStart + 6;
        if (pageEnd > pageCount)
        {
            pageEnd = pageCount;
        }
        var sb = new StringBuilder();
        if (pageNumber > 1 && pageNumber <= pageCount)
        {
            sb.AppendLine("<li><a href=" + pageUrl(pageNumber - 1) + ">←</a></li>");
        }
        for (var i = pageStart; i <= pageEnd; i++)
        {
            if (i == pageNumber)
            {
                sb.AppendLine("<li class=" + "active" + "><a href=" + pageUrl(i) + ">" + i + "</a></li>");
            }
            else
                sb.AppendLine("<li><a href=" + pageUrl(i) + ">" + i + "</a></li>");
        }
        if (pageNumber < pageCount)
        {
            sb.AppendLine("<li><a href=" + pageUrl(pageNumber + 1) + ">→</a></li>");
        }
        return MvcHtmlString.Create(sb.ToString());
    }

    public static MvcHtmlString TagCloud(this HtmlHelper htmlHelper, List<Tag> tags)
    {
        var sb = new StringBuilder();
        var tagsHelper = new Tag[tags.Count];
        tags.CopyTo(tagsHelper);
        var random = new Random();
        var count = tags.Count;
        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        while (count>=1)
        {
            var index = random.Next(1, count);
            var p = 0;
            for (var i = 0; i < tagsHelper.Length; i++)
            {
                if (tagsHelper[i].Name == tags[index-1].Name)
                {
                    p = i;
                }
            }
            sb.Append(string.Format("<li class='ref-{0}cat'><a href=\"{1}\">{2}</a></li>",6 - Math.Round(Convert.ToDouble((p+1)/2f), MidpointRounding.AwayFromZero), urlHelper.Action("Index", "News", new { id = "", tag = tags[index - 1].Name }), tags[index - 1].Name));
            tags.RemoveAt(index-1);
            count = tags.Count;
        }       
        return MvcHtmlString.Create(sb.ToString());
    }
}